import { KWCode } from "../common/code";
import { KWError } from "../common/error";
import { ReturnModelType } from '@typegoose/typegoose';
import { stores } from 'koa-session';
import * as moment from 'moment';
import { SessionEntity, SessionModel } from '../entity/session.entity';
import { SESSION_MAX_AGE } from '../constants';

export default class SessionMongoStore implements stores {
  private session: ReturnModelType<typeof SessionEntity>;
  private expires: number = SESSION_MAX_AGE;
  private options: {
    rolling?: boolean;
    signed?: boolean;
  } = {
    rolling: true,
    signed: false
  }
  constructor(expires?: number, options?: {rolling?: boolean; signed?: boolean;}) {
    if (expires) { this.expires = expires; }
    if (options) {
      if (options.rolling) {
        this.options.rolling = options.rolling;
      }

      if (options.signed) {
        this.options.signed = options.signed;
      }
    }
    this.session = SessionModel;
  }
  async set(id: string, data: Object) {
    const session = Object.assign({}, data, {expires_in: new Date(moment().unix() * 1000 + this.expires )})
    if (this.options.rolling) {
      return await this.session.updateOne({ id }, session, { upsert: true });
    }
    return session;
  }

  async get(id: string) {
    try {
      const session = await this.session.findOne({ id }, { _id: 0 });
      if (session) {
        return session.toJSON();
      }
    } catch (error) {
      throw new KWError(KWCode.internalError, `SessionStore Error: ${error}`);
    }
  }

  async destroy(id: string) {
    return this.session.remove({ id });
  }

}